package com.sgy.netty.route;

import com.alibaba.fastjson.JSON;
import com.sgy.common.ApiResult;
import com.sgy.common.ImRequest;
import com.sgy.common.proto.MsgProtocol;
import com.sgy.netty.business.MsgProc;
import com.sgy.netty.business.UserProc;
import com.sgy.pojo.Visitor;
import com.sgy.util.Constants;
import com.sgy.util.DateUtil;
import com.sgy.util.RedisUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;
import java.util.Date;

public class MsgRoute {
    @Autowired
    private UserProc userProc;
    @Autowired
    private MsgProc msgProc;

    public ApiResult distribute(ChannelHandlerContext ctx,String request){
        ApiResult result = null;
        //安全防护
        InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = address.getAddress().getHostAddress();
        String bv = RedisUtil.hget(Constants.blackMap,clientIP);
        if(!StringUtils.isEmpty(bv)){
            result = ApiResult.fail("你已被列入黑名单，无法访问系统");
            ctx.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(result)));
            return result;
        }
        //上次访问时间
        String visited = RedisUtil.hget(Constants.accessTimeMap,clientIP);
        Visitor visitor = null;
        if(StringUtils.isNotEmpty(visited)){
            visitor = JSON.parseObject(visited,Visitor.class);
            //超过非法次数后拉黑
            if(visitor.getIllegalCount()>=Constants.illegalCount){
                RedisUtil.hset(Constants.blackMap,clientIP,"1");
                Date now = new Date();
                Long second = (Long) DateUtil.getDistanceTime(visitor.getLastTime(), now).get(3);
                if(second<=Constants.timeInterval){
                    visitor.setIllegalCount(visitor.getIllegalCount()+1);
                }
            }
        }else {
            visitor = new Visitor();
            visitor.setIp(clientIP);
            visitor.setIllegalCount(0);
        }
        visitor.setLastTime(new Date());

        RedisUtil.hset(Constants.accessTimeMap,clientIP,JSON.toJSONString(visitor));

        ImRequest req = JSON.parseObject(request,ImRequest.class);
        if(req.getUrl().equals(MsgProtocol.all_user)){
            result = msgProc.groupMsg(ctx,req);
            return result;
        }

        if(req.getUrl().equals(MsgProtocol.get_line_num)){
            result = userProc.getLineNum(ctx,req);
            return result;
        }
        return result;
    }
}
